
import pygame
import asyncio
from random import randint as ri
from random import choice
import os
import mods.CrystalLib
import mods.printlib
import Shaders.blockworld
import json
from random import uniform

block_hard = []
block_soft = []
block_void = []
block_bed  = []
item_bomb  = []  # not fine.
item_bbs   = {}  # special image, drawing by pygame.
item_tnt   = []
entity_0   = {'west':None, 'north':None, 'south':None, 'east':None}
item_ice_thorn = [] # len = 3
effect_cold = None
#entity_1   = []
#entity_2   = []
#entity_3   = []
'''2024 01 03'''
addon_powerbottle = []
addon_capacity = []
addon_tnt = []
addon_shield = []
addon_rocket = []
addon_diamond = []
Mine_img : list = []
Minemashed_img : list = []

__Root = "E:\\Environments\\pygame\\Qbomb\\resourcepacks\\"
H = __Root + "origin\\"

block_hard_0 = pygame.Surface((60, 60))
block_hard_0.fill((10, 10, 20))
block_soft_0 = pygame.Surface((60, 60))
block_soft_0.fill((180, 120, 30))
block_void_0 = pygame.Surface((60, 60))
block_void_0.fill((ri(220, 255), ri(220, 255), ri(220, 255)))
block_bed_0 = pygame.Surface((60, 60))
block_bed_0.fill((255, 255, 255))
pygame.draw.rect(block_bed_0, (0, 255, 0), (6, 6, 48, 48))
item_tnt_0 = pygame.Surface((48, 48))
item_tnt_0.fill((255, 0, 0))
mods.printlib.CenterPrint1('TNT', (255, 255, 255), (24, 24), item_tnt_0)
addon_tnt_0 = pygame.Surface((48, 48))
addon_tnt_0.fill((0, 255, 255))
mods.printlib.CenterPrint1('TNT', (255, 255, 255), (24, 24), addon_tnt_0)

ice_color = (0x79, 0xff, 0xff)
ice_0 = pygame.Surface((60, 60))
ice_0.fill((255, 255, 255))
pygame.draw.polygon(ice_0, ice_color, ((3, 0), (12, 10), (21, 0)))
pygame.draw.polygon(ice_0, ice_color, ((21, 0), (30, 15), (39, 0)))
pygame.draw.polygon(ice_0, ice_color, ((39, 0), (48, 10), (57, 0)))
ice_0.set_colorkey((255, 255, 255))

ice_1 = pygame.Surface((60, 60))
ice_1.fill((255, 255, 255))
pygame.draw.polygon(ice_1, ice_color, ((3, 0), (12, 25), (21, 0)))
pygame.draw.polygon(ice_1, ice_color, ((21, 0), (30, 38), (39, 0)))
pygame.draw.polygon(ice_1, ice_color, ((39, 0), (48, 25), (57, 0)))
ice_1.set_colorkey((255, 255, 255))

ice_2 = pygame.Surface((60, 60))
ice_2.fill((255, 255, 255))
pygame.draw.polygon(ice_2, ice_color, ((3, 0), (12, 38), (21, 0)))
pygame.draw.polygon(ice_2, ice_color, ((21, 0), (30, 56), (39, 0)))
pygame.draw.polygon(ice_2, ice_color, ((39, 0), (48, 38), (57, 0)))
ice_2.set_colorkey((255, 255, 255))

item_ice_thorn.append(ice_0)
item_ice_thorn.append(ice_1)
item_ice_thorn.append(ice_2)

isLoadingResource = False
LoadingResourcePersent = 0 # 0 ~ 100

async def load_resource():
    global isLoadingResource, LoadingResourcePersent
    isLoadingResource = True
    imgs = os.listdir(H)
    index = 0
    Sleep_Time = 0.01
    ADDs = 6
    
    block_hard.append(block_hard_0)
    index += 1
    LoadingResourcePersent = mods.CrystalLib.cint(index / (len(imgs) + ADDs) * 100)
    await asyncio.sleep(Sleep_Time)
    
    block_soft.append(block_soft_0)
    index += 1
    LoadingResourcePersent = mods.CrystalLib.cint(index / (len(imgs) + ADDs) * 100)
    await asyncio.sleep(Sleep_Time)
    
    block_void.append(block_void_0)
    index += 1
    LoadingResourcePersent = mods.CrystalLib.cint(index / (len(imgs) + ADDs) * 100)
    await asyncio.sleep(Sleep_Time)
    
    block_bed.append(block_bed_0)
    index += 1
    LoadingResourcePersent = mods.CrystalLib.cint(index / (len(imgs) + ADDs) * 100)
    await asyncio.sleep(Sleep_Time)
    
    item_tnt.append(item_tnt_0)
    index += 1
    LoadingResourcePersent = mods.CrystalLib.cint(index / (len(imgs) + ADDs) * 100)
    await asyncio.sleep(Sleep_Time)
    
    addon_tnt.append(addon_tnt_0)
    index += 1
    LoadingResourcePersent = mods.CrystalLib.cint(index / (len(imgs) + ADDs) * 100)
    await asyncio.sleep(Sleep_Time)
    
    for img in imgs:
        await asyncio.sleep(Sleep_Time)
        index += 1
        LoadingResourcePersent = mods.CrystalLib.cint(index / (len(imgs) + ADDs) * 100)
        isLoadingResource = True
        sur0 = pygame.image.load(H + img).convert()
        if img[0:5] == 'block':
            if img[5:10] == '_hard':
                sur = pygame.transform.scale(sur0, (60, 60))
                block_hard.append(sur)
            elif img[5:10] == '_soft':
                sur = pygame.transform.scale(sur0, (60, 60))
                block_soft.append(sur)
            elif img[5:10] == '_void':
                sur = pygame.transform.scale(sur0, (60, 60))
                block_void.append(sur)
            elif img[5:9]  == '_bed':
                sur = pygame.transform.scale(sur0, (60, 60))
                block_bed.append(sur)
        elif img[0:4] == 'item':
            if img[4:9] == '_bomb':
                sur = pygame.transform.scale(sur0, (60, 60))
                item_bomb.append(sur)
            elif img[4:8] == '_tnt':
                sur = pygame.transform.scale(sur0, (48, 48))
                item_tnt.append(sur)
        elif img[0:8] == 'entity_0':
            # eg: entity_0_west.png
            imgname = img.split('.')[0]
            toward = imgname.split('_')[-1]
            sur = pygame.transform.scale(sur0, (60, 100))
            sur.set_colorkey((255, 255, 255))
            entity_0[toward] = sur
        elif img.startswith('apple'):
            sur = pygame.transform.scale(sur0, (48, 48))
            sur.set_colorkey((255, 255, 255))
            addon_capacity.append(sur)
        elif img.startswith('powerbottle'):
            sur = pygame.transform.scale(sur0, (48, 48))
            sur.set_colorkey((255, 255, 255))
            addon_powerbottle.append(sur)
        elif img.startswith('shield'):
            sur = pygame.transform.scale(sur0, (48, 48))
            sur.set_colorkey((255, 255, 255))
            addon_shield.append(sur)
        elif img.startswith('rocket'):
            sur = pygame.transform.scale(sur0, (48, 48))
            #sur.set_colorkey((255, 255, 255))
            addon_rocket.append(sur)
        elif img.startswith('diamond'):
            sur = pygame.transform.scale(sur0, (48, 48))
            sur.set_colorkey((255, 255, 255))
            addon_diamond.append(sur)
        elif img.startswith('minemashed'):
            sur = pygame.transform.scale(sur0, (48, 48))
            sur.set_colorkey((255, 255, 255))
            Minemashed_img.append(sur)
        elif img.startswith('mine'):
            sur = pygame.transform.scale(sur0, (48, 48))
            sur.set_colorkey((255, 255, 255))
            Mine_img.append(sur)
    isLoadingResource = False
    return True
    
_screen = None

async def onLoadingScreen():
    global isLoadingResource
    c0 = (ri(200, 255), ri(200, 255), ri(200, 255))
    c1, c2 = mods.CrystalLib.RandomColor(), mods.CrystalLib.RandomColor()
    while isLoadingResource == True:
        await asyncio.sleep(0.00001)
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                pass
            if event.type == pygame.KEYDOWN:
                Ellipsis
        pygame.draw.rect(_screen, c0, (0, 0, 1200, 900))
        pygame.draw.rect(_screen, c1, (295, 680, 610, 40))
        pygame.draw.rect(_screen, c2, (300, 685, mods.CrystalLib.cint(LoadingResourcePersent * 6), 30))
        mods.printlib.xyprint('正在加载资源, 请稍后···', c2, ('center', 8))
        if isLoadingResource == False:
            return
        pygame.display.flip()

async def LoadResourceMain():
    global isLoadingResource
    isLoadingResource = True
    tasks = [onLoadingScreen(), load_resource()]
    await asyncio.gather( *tasks )

def RELOAD_RESOURCE():
    asyncio.run(LoadResourceMain())
    if len(addon_capacity) == 0 or len(addon_powerbottle) == 0:
        raise ValueError('缺失必要的材质')

def inits(screen):
    global _screen
    _screen = screen
    RELOAD_RESOURCE()
    return 'Reload Resource Pack', RELOAD_RESOURCE

_block_hard_now = None
_block_soft_now = None
_block_void_now = None
_block_bed_now  = None
_item_tnt       = None
_apple    = None
_power    = None
_addonTNT = None
_addonShield = None

_addonRocket = None
_MovingRocket : dict = {
    'north': None, 'west': None, 'south': None, 'east': None
}

_addonDiamond = None
_MineImgNow = None
_MineMashedImgNow = None

__MovingRct = pygame.Surface((48, 48))
def flush_resource_now():
    global _block_hard_now, _block_soft_now, _block_void_now, _block_bed_now, _item_tnt
    global _apple, _power, _addonTNT, _addonShield, _addonRocket, _MovingRocket, _addonDiamond, _MineImgNow, _MineMashedImgNow
    _block_hard_now = choice(block_hard)
    _block_soft_now = choice(block_soft)
    _block_void_now = choice(block_void)
    _block_bed_now  = choice(block_bed)
    _item_tnt       = choice(item_tnt)
    _apple = choice(addon_capacity)
    _power = choice(addon_powerbottle)
    _addonTNT = choice(addon_tnt)
    _addonShield = choice(addon_shield)
    __MovingRct.fill((255, 255, 255))
    __MovingRct.blit(choice(addon_rocket), (0, 0))
    _addonRocket = __MovingRct
    _MovingRocket["north"] = _addonRocket
    _MovingRocket["west"] = pygame.transform.rotate(__MovingRct, 90)
    _MovingRocket["south"] = pygame.transform.flip(__MovingRct, False, True)
    _MovingRocket["east"] = pygame.transform.flip(_MovingRocket["west"], True, False)
    for i in ('north', 'west', 'south', 'east'):
        _MovingRocket[i].set_colorkey((255, 255, 255))
    _addonDiamond = choice(addon_diamond)
    _MineImgNow = choice(Mine_img)
    _MineMashedImgNow = choice(Minemashed_img)

def draw_block(x, y, dtype, screen):
    # x=1~20,  y=1~15
    #global screen
    if dtype == mods.CrystalLib.Void:
        screen.blit(_block_void_now, (mods.CrystalLib.cint(x*60), mods.CrystalLib.cint(y*60)))
    elif dtype == mods.CrystalLib.Soft:
        screen.blit(_block_soft_now, (mods.CrystalLib.cint(x*60), mods.CrystalLib.cint(y*60)))
    elif dtype == mods.CrystalLib.Hard:
        screen.blit(_block_hard_now, (mods.CrystalLib.cint(x*60), mods.CrystalLib.cint(y*60)))
    elif dtype == mods.CrystalLib.Bed:
        screen.blit(_block_bed_now, (mods.CrystalLib.cint(x*60), mods.CrystalLib.cint(y*60)))
    elif dtype == mods.CrystalLib.BB:
        pygame.draw.rect(screen, (255, 90, 60), (mods.CrystalLib.cint(x*60), mods.CrystalLib.cint(y*60), 60, 60))
    else:
        mods.CrystalLib.print_warning(f'无法加载的区块: ({x}, {y}, {dtype}).')

def draw_entity(who, screen):
    if who.ID == 0:
        if None in [entity_0['west'], entity_0['north'], entity_0['south'], entity_0['east']]:
            pygame.draw.ellipse(screen, (0, 0x80, 0xff),
                            (mods.CrystalLib.cint(who.x*60 + who.xp), mods.CrystalLib.cint(who.y*60 + who.yp + 10), 60, 40))
        else:
            screen.blit(entity_0[who.towards],
                        (mods.CrystalLib.cint(who.x*60 + who.xp), mods.CrystalLib.cint(who.y*60 + who.yp -40)))
    elif who.ID == 1:
        pygame.draw.ellipse(screen, mods.cfg.color_e1,
                            (mods.CrystalLib.cint(who.x*60 + who.xp), mods.CrystalLib.cint(who.y*60 + who.yp + 10), 60, 40))
    elif who.ID == 2:
        pygame.draw.ellipse(screen, mods.cfg.color_e2,
                            (mods.CrystalLib.cint(who.x*60 + who.xp), mods.CrystalLib.cint(who.y*60 + who.yp + 10), 60, 40))
    elif who.ID == 3:
        pygame.draw.ellipse(screen, mods.cfg.color_e3,
                            (mods.CrystalLib.cint(who.x*60 + who.xp), mods.CrystalLib.cint(who.y*60 + who.yp + 10), 60, 40))

def draw_item(who, screen):
    match who.ID:
        case 4:
            #Bomb
            pygame.draw.rect(screen, who.color, (mods.CrystalLib.cint(who.x*60), mods.CrystalLib.cint(who.y*60), 60, 60))
        case 5:
            pygame.draw.rect(screen, who.color, (mods.CrystalLib.cint(who.x*60), mods.CrystalLib.cint(who.y*60), 60, 60))
            if who.towards == 1:
                Ellipsis
            #    pygame.draw.rect(screen, (255,255,255), (CrystalLib.cint(who.x*60+20), CrystalLib.cint(who.y*60), 20, 60))
            elif who.towards == 2:
                Ellipsis
            #    pygame.draw.rect(screen, (255,255,255), (CrystalLib.cint(who.x*60), CrystalLib.cint(who.y*60+20), 60, 20))
            else:
                pygame.draw.rect(screen, (255,255,255), (mods.CrystalLib.cint(who.x*60+20), mods.CrystalLib.cint(who.y*60), 20, 60))
                pygame.draw.rect(screen, (255,255,255), (mods.CrystalLib.cint(who.x*60), mods.CrystalLib.cint(who.y*60+20), 60, 20))
        case 6:
            if who.vy <= who.VY:
                screen.blit(_item_tnt, (mods.CrystalLib.cint(who.x*60 + 6), mods.CrystalLib.cint(who.y*60 + 6)))
            else:
                screen.blit(_item_tnt, (mods.CrystalLib.cint(who.xpos + 6), mods.CrystalLib.cint(who.ypos + 6)))
        case 7:
            # ice thorn
            screen.blit(item_ice_thorn[who.state], (mods.CrystalLib.cint(who.x*60 ), mods.CrystalLib.cint(who.y*60 )))
        case 8:
            screen.blit(
                _MovingRocket[who.direct], (mods.CrystalLib.cint(who.x ), mods.CrystalLib.cint(who.y ))
            )
        case 9:
            if who.blast == None:
                if who.set_time > 0:
                    who.set_time -= 1
                    if 0 <= (who.set_time % 50) <= 24:
                        screen.blit(
                            _MineImgNow, (mods.CrystalLib.cint(who.x*60 + 6), mods.CrystalLib.cint(who.y*60 + 6))
                        )
                        
                    else:
                #        screen.blit(
                #    _MineMashedImgNow, (mods.CrystalLib.cint(who.x*60 + 6), mods.CrystalLib.cint(who.y*60 + 6))
                #)
                        pass
            else:
                screen.blit(
                    _MineMashedImgNow, (mods.CrystalLib.cint(who.x*60 + 6), mods.CrystalLib.cint(who.y*60 + 6))
                )
        case _:
            mods.CrystalLib.print_warning(f'无法加载的item: ({who.ID}).')
            raise RuntimeError('crash.')

#addons(MA_xxx)
MA_NULL = 0
MA_APPLE = 1
MA_POWER = 2
MA_TNT  = 3
MA_SHIELD = 4
MA_ROCKET = 5
MA_DIAMOND = 6
MA_LANDMINE = 7

def draw_addon(x, y, dtype, screen):
    # x=1~20,  y=1~15
    #global screen
    if dtype == MA_NULL:
        pass
    elif dtype == MA_APPLE:
        screen.blit(_apple, (mods.CrystalLib.cint(x*60+6), mods.CrystalLib.cint(y*60+6)))
    elif dtype == MA_POWER:
        screen.blit(_power, (mods.CrystalLib.cint(x*60+6), mods.CrystalLib.cint(y*60+6)))
    elif dtype == MA_TNT:
        screen.blit(_addonTNT, (mods.CrystalLib.cint(x*60+6), mods.CrystalLib.cint(y*60+6)))
    elif dtype == MA_SHIELD:
        screen.blit(_addonShield, (mods.CrystalLib.cint(x*60+6), mods.CrystalLib.cint(y*60+6)))
    elif dtype == MA_ROCKET:
        screen.blit(_addonRocket, (mods.CrystalLib.cint(x*60+6), mods.CrystalLib.cint(y*60+6)))
    elif dtype == MA_DIAMOND:
        screen.blit(_addonDiamond, (mods.CrystalLib.cint(x*60+6), mods.CrystalLib.cint(y*60+6)))
    elif dtype == MA_LANDMINE:
        screen.blit(_MineImgNow, (mods.CrystalLib.cint(x*60+6), mods.CrystalLib.cint(y*60+6)))
    else:
        mods.CrystalLib.print_warning(f'无法加载的addon: ({x}, {y}, {dtype}).')
        raise RuntimeError('crash.')

effect_slow_pic = pygame.Surface((30, 30))
effect_slow_pic.fill((0xfa, 0xbb, 0x45))
pygame.draw.rect(effect_slow_pic, (255, 255, 255), (0, 0, 30, 30), width = 1)
color_rdGrey = ri(80, 180)
random_grey = tuple([color_rdGrey for i in range(3)])
pygame.draw.ellipse(effect_slow_pic, random_grey, (4, 8, 22, 14))

effect_shield_pic = pygame.Surface((30, 30))
pygame.draw.rect(effect_shield_pic, (255, 255, 255), (0, 0, 30, 30), width = 1)
pygame.draw.rect(effect_shield_pic, (0xfc, 0xc8, 0x3f), (8, 4, 14, 22))

def draw_pic(which, pos : tuple, screen):
    if which not in ('effect_slow', 'effect_shield'):
        Shaders.blockworld.draw_pic(which, pos, screen)
    else:
        if which == 'effect_slow':
            screen.blit(effect_slow_pic, pos)
        elif which == 'effect_shield':
            screen.blit(effect_shield_pic, pos)
        else:
            Shaders.blockworld.draw_pic(which, pos, screen)
# wow

PARTICLE : dict =                                                                         \
{
    #
}
JADE : dict = {}

def set_init():
    global PARTICLE, JADE
    strstr = ''
    with open('.\\Shaders\\jade.tt', "r" , encoding='utf-8') as fs:
        strstr = fs.read()
    JADE = json.loads(strstr)
    PARTICLE = JADE["particle"]
    mods.CrystalLib.printm(f'Load textures:{JADE["name"]} for {JADE["version"]}')

def draw_particle_enderpearl(x: int, y: int):
    d : dict = PARTICLE["enderpearl"]
    match d["shape"]:
        case "fillcircle":
            pygame.draw.circle(_screen, d["color"], (ri(x - 12, x + 12), ri(y - 12, y + 12)), uniform(d["length"][0],d["length"][1]))
            pygame.draw.circle(_screen, d["color"], (ri(x - 12, x + 12), ri(y - 12, y + 12)), uniform(d["length"][0],d["length"][1]))
            pygame.draw.circle(_screen, d["color"], (ri(x - 12, x + 12), ri(y - 12, y + 12)), uniform(d["length"][0],d["length"][1]))
        case "circle":
            pygame.draw.circle(_screen, d["color"], (ri(x - 12, x + 12), ri(y - 12, y + 12)), uniform(d["length"][0],d["length"][1]), 1)
            pygame.draw.circle(_screen, d["color"], (ri(x - 12, x + 12), ri(y - 12, y + 12)), uniform(d["length"][0],d["length"][1]), 1)
            pygame.draw.circle(_screen, d["color"], (ri(x - 12, x + 12), ri(y - 12, y + 12)), uniform(d["length"][0],d["length"][1]), 1)
        case _:
            pygame.draw.rect(_screen, d["color"], (ri(x - 12, x + 12), ri(y - 12, y + 12), ri(d["length"][0],d["length"][1]), ri(d["length"][0],d["length"][1])))
            pygame.draw.rect(_screen, d["color"], (ri(x - 12, x + 12), ri(y - 12, y + 12), ri(d["length"][0],d["length"][1]), ri(d["length"][0],d["length"][1])))
            pygame.draw.rect(_screen, d["color"], (ri(x - 12, x + 12), ri(y - 12, y + 12), ri(d["length"][0],d["length"][1]), ri(d["length"][0],d["length"][1])))

#flush_resource_now()
__sf_main = pygame.Surface((1200, 900))
def sf_main_load():
    global __sf_main
    __sf_main.fill((255, 240, 255))
    F = pygame.font.SysFont('华文仿宋', 20)
    x : int = 169
    for v in block_void:
        __sf_main.blit(v, (x, 200))
        x += 100
    t = F.render('Air Block. 可以直接穿过的空气区域。', True, mods.CrystalLib.RandomColor())
    __sf_main.blit(t, (169, 269))
    x = 169
    for v in block_soft:
        __sf_main.blit(v, (x, 300))
        x += 100
    t = F.render('Soft Block. 可以被摧毁的方块, Normal模式下会获得战利品。', True, mods.CrystalLib.RandomColor())
    __sf_main.blit(t, (169, 369))
    x = 169
    for v in block_hard:
        __sf_main.blit(v, (x, 400))
        x += 100
    t = F.render('Hard Block. 无法被摧毁的坚固方块。', True, mods.CrystalLib.RandomColor())
    __sf_main.blit(t, (169, 469))
    ...
    t = F.render('Single player: ↑↓←→移动, 空格:炸弹, R:炸弹小飞机, T:TNT, M:地雷',True,mods.CrystalLib.RandomColor())
    __sf_main.blit(t, (169, 800))
    t = F.render(
'Double player: P1: ↑↓←→移动, R-Enter:炸弹, 0:TNT, 1:地雷, 2:火箭; P2:WASD移动, 空格:炸弹, R:火箭, T:TNT, Y:地雷',
        True, mods.CrystalLib.RandomColor()
    )
    __sf_main.blit(t, (169, 850))
#__sf_main_load()
def Illustrate(SCR: pygame.surface.Surface):
    while True:
        pygame.time.wait(50)
        SCR.blit(__sf_main, (0, 0))
        pygame.display.update()
        for e in pygame.event.get():
            if e.type == pygame.QUIT:
                return
    